package br.fbv.compreja.negocio.infra;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.net.URI;
import java.net.UnknownHostException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;

import android.util.Log;
import br.fbv.compreja.activity.base.BuzzException;

public class GetHttp {
	public String page = "";

	public GetHttp(String URL) throws Exception, UnknownHostException,
			SocketException, RuntimeException {
		BufferedReader bufferedReader = null;
		try {
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
					"android");
			HttpGet request = new HttpGet();
			request.setHeader("Content-Type", "text/plain; charset=utf-8");
			request.setURI(new URI(URL));
			HttpResponse response = client.execute(request);
			bufferedReader = new BufferedReader(new InputStreamReader(response
					.getEntity().getContent()));
			StringBuffer stringBuffer = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");

			Log.d("GetHttp", "Iniciando leitura de buffer.");
			while ((line = bufferedReader.readLine()) != null) {
				stringBuffer.append(line + NL);
				Log.d("GetHttp", stringBuffer.toString());
			}
			bufferedReader.close();
			Log.d("GetHttp", "Leitura de buffer finalizada");

			page = stringBuffer.toString();
		} catch (RuntimeException e) {
			Log.e("GetHttp", e.toString());
			e.printStackTrace();
			throw new BuzzException("Sem conexão com Internet", e);
		} catch (UnknownHostException e) {
			Log.e("GetHttp", e.toString());
			e.printStackTrace();
			throw new BuzzException("Sem conexão com Internet", e);
		} catch (SocketException e) {
			e.printStackTrace();
			Log.e("GetHttp", e.toString());
			throw new BuzzException("Erro de conexão");
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("GetHttp", e.toString());
			throw new BuzzException("Erro Catastrofico", e);
		} catch (Throwable e) {
			Log.e("GetHttp", e.toString());
			e.printStackTrace();
			throw new BuzzException("Throwable", e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					Log.e("GetHttp", e.toString());
				} catch (Throwable e) {
					Log.e("GetHttp", e.toString());
					e.printStackTrace();
					throw new BuzzException("Fudeu!", e);
				}
			}
		}
	}
}
